package cn.ilovese.collect.serviceimpl.transaction;

import cn.ilovese.collect.datamapper.transaction.TransactionMapper;
import cn.ilovese.collect.datamapper.user.UserMapper;
import cn.ilovese.collect.datamapper.user.WorkerLevelHistoryMapper;
import cn.ilovese.collect.po.transaction.Transaction;
import cn.ilovese.collect.po.user.User;
import cn.ilovese.collect.po.user.WorkerLevelHistory;
import cn.ilovese.collect.service.transaction.TransactionService;
import cn.ilovese.collect.util.Constant;
import cn.ilovese.collect.vo.NullVO;
import cn.ilovese.collect.vo.ResultVO;
import cn.ilovese.collect.vo.transaction.TransactionDetailVO;
import cn.ilovese.collect.vo.transaction.TransactionFormVO;
import cn.ilovese.collect.vo.user.WorkerLevelHistoryVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TransactionServiceImpl implements TransactionService {

    @Resource
    UserMapper userMapper;

    @Resource
    TransactionMapper transactionMapper;

    @Resource
    WorkerLevelHistoryMapper workerLevelHistoryMapper;

    @Override
    public ResultVO<String> getUserBalance(Integer userId) {
        User userWithBalance=userMapper.selectByPrimaryKey(userId);
        if(userWithBalance!=null){
            String balance = String.format("%.2f", userWithBalance.getBalance());
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"获取用户余额",balance);
        }
        return new ResultVO<>(Constant.REQUEST_FAIL,"获取用户余额失败");
    }

    @Override
    public ResultVO<NullVO> chargeByBoss(TransactionFormVO transactionFormVO) {
        User bossWithBalance=userMapper.selectByPrimaryKey(transactionFormVO.getUserId());
        BigDecimal oldBalance = new BigDecimal(Double.toString(bossWithBalance.getBalance()));
        BigDecimal amount = new BigDecimal(Double.toString(transactionFormVO.getAmount()));
        bossWithBalance.setBalance(oldBalance.add(amount).doubleValue());
        int updateRow=userMapper.updateByPrimaryKey(bossWithBalance);
        if (updateRow==1) {
            long timeNow = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date nowTime=new Date();
            String nowDate = sdf.format(nowTime);
            String transactionNumber = "CH" + nowDate + timeNow;
            Transaction chargeTransaction = new Transaction();
            chargeTransaction.setTransactionNumber(transactionNumber);
            chargeTransaction.setBalance(bossWithBalance.getBalance());
            chargeTransaction.setIn(transactionFormVO.getAmount());
            chargeTransaction.setOut(0);
            chargeTransaction.setRemark("发包方"+bossWithBalance.getUsername()+"充值");
            chargeTransaction.setTime(nowTime);
            chargeTransaction.setType("个人充值");
            chargeTransaction.setUserId(bossWithBalance.getId());
            int id=transactionMapper.insert(chargeTransaction);
            if(id>0){
                return new ResultVO<>(Constant.REQUEST_SUCCESS,"充值成功", new NullVO());
            }
            else{
                return new ResultVO<>(Constant.REQUEST_FAIL,"记录单号失败", new NullVO());
            }
        }else{
            return new ResultVO<>(Constant.REQUEST_FAIL,"充值失败");
        }
    }

    @Override
    public ResultVO<NullVO> withdrawByWorker(TransactionFormVO transactionFormVO) {
        User workerWithBalance=userMapper.selectByPrimaryKey(transactionFormVO.getUserId());
        BigDecimal oldBalance = new BigDecimal(Double.toString(workerWithBalance.getBalance()));
        BigDecimal amount = new BigDecimal(Double.toString(transactionFormVO.getAmount()));
        workerWithBalance.setBalance(oldBalance.subtract(amount).doubleValue());
        if(workerWithBalance.getBalance()<0){
            return new ResultVO<>(Constant.REQUEST_FAIL,"提现失败，余额不足", new NullVO());
        }
        int updateRow=userMapper.updateByPrimaryKey(workerWithBalance);
        if (updateRow==1) {
            long timeNow = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date nowTime=new Date();
            String nowDate = sdf.format(nowTime);
            String transactionNumber = "WD" + nowDate + timeNow;
            Transaction withdrawTransaction = new Transaction();
            withdrawTransaction.setTransactionNumber(transactionNumber);
            withdrawTransaction.setBalance(workerWithBalance.getBalance());
            withdrawTransaction.setOut(transactionFormVO.getAmount());
            withdrawTransaction.setIn(0);
            withdrawTransaction.setRemark("工人 "+workerWithBalance.getUsername()+" 提现");
            withdrawTransaction.setTime(nowTime);
            withdrawTransaction.setType("个人提现");
            withdrawTransaction.setUserId(workerWithBalance.getId());
            int id=transactionMapper.insert(withdrawTransaction);
            if(id>0){
                return new ResultVO<>(Constant.REQUEST_SUCCESS,"提现成功", new NullVO());
            }
            else{
                return new ResultVO<>(Constant.REQUEST_FAIL,"记录单号失败", new NullVO());
            }
        }else{
            return new ResultVO<>(Constant.REQUEST_FAIL,"提现失败");
        }
    }

    @Override
    public ResultVO<List<TransactionDetailVO>> getUserTransactionDetails(Integer userId, Long startTime, Long endTime) {
        Date startDate=new Date(startTime);
        Date endDate=new Date(endTime);
        List<Transaction> userTransactionDetails=transactionMapper.selectByUser(userId);
        List<TransactionDetailVO> res=new ArrayList<>();
        if(userTransactionDetails!=null){
            for(Transaction transactionDetail:userTransactionDetails){
                if(transactionDetail.getTime().compareTo(startDate) > 0 && transactionDetail.getTime().compareTo(endDate)<0)
                    res.add(new TransactionDetailVO(transactionDetail));
            }
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"查询交易条目成功",res);
        }else{
            return new ResultVO<>(Constant.REQUEST_FAIL,"查询交易条目失败");
        }
    }

    @Override
    public ResultVO<List<WorkerLevelHistoryVO>> getWorkerLevelHistory(Integer userId) {
        List<WorkerLevelHistory> workerLevelHistories=workerLevelHistoryMapper.selectByUser(userId);
        List<WorkerLevelHistoryVO> res=new ArrayList<>();
        if(workerLevelHistories!=null){
            for(WorkerLevelHistory workerLevelHistory:workerLevelHistories){
                res.add(new WorkerLevelHistoryVO(workerLevelHistory));
            }
            return new ResultVO<>(Constant.REQUEST_SUCCESS,"查询等级历史变更条目成功",res);
        }else{
            return new ResultVO<>(Constant.REQUEST_FAIL,"查询等级历史变更条目失败");
        }
    }
}
